<template>
    <el-container class="jxc_buy_return_bill_container">
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleHeaderEvent">
                    <template slot="right_search">
                        <el-select v-model="searchForm.audit_state" placeholder="请选择"
                                   class="w100" clearable @change="getList(true)"
                                   style="margin-right: 5px;">
                            <el-option v-for="(item, index) in stateList"
                                       :key="index" :label="item.label" :value="item.value" />
                        </el-select>
                    </template>
                </headerTemplate>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent" />
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import poiApi from "@common/api/poiApi";
import BuyReturnBillForm from "../components/BuyReturnBillForm";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "JxcBuyReturnBill",
    data() {
        const _this = this;
        return {
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getList();
                        },
                    },
                    {
                        id: "add",
                        icon: "fa fa-plus",
                        type: "primary",
                        show: true,
                        permission: "jxc:buyReturn:save",
                        method: () => {
                            _this.openDialog(null, 'add');
                        },
                    },
                    {
                        id: "edit",
                        icon: "fa fa-pencil",
                        type: "success",
                        show: true,
                        permission: "jxc:buyReturn:save",
                        method: () => {
                            _this.openDialog(null, 'edit');
                        },
                    },
                    {
                        id: "delete",
                        icon: "fa fa-trash-o",
                        type: "danger",
                        show: true,
                        permission: "jxc:buyReturn:delete",
                        method: () => {
                            _this.deleteConfirm();
                        },
                    },
                    {
                        id: "audit",
                        label: '审核',
                        icon: "el-icon-top-right",
                        class: 'audit_btn',
                        show: true,
                        permission: "jxc:buyReturn:audit",
                        method: () => {
                            _this.changeAuditState('audit');
                        },
                    },
                    {
                        id: "reAudit",
                        label: '反审',
                        icon: "el-icon-bottom-left",
                        class: 're_audit_btn',
                        show: true,
                        permission: "jxc:buyReturn:reAudit",
                        method: () => {
                            _this.changeAuditState('reAudit');
                        },
                    },
                    {
                        id: "gen_stock_out_bill",
                        type: "success",
                        show: true,
                        permission: "jxc:buyReturn:genOutBill",
                        label: '生成出库单',
                        method: () => {
                            _this.genOutBill();
                        },
                    },
                    {
                        id: "export",
                        type: "warning",
                        icon: "el-icon-download",
                        label: '导出',
                        class: 'export_btn',
                        show: true,
                        permission: "jxc:buyReturn:export",
                        btnType: 'dropdown',
                        dropdownItems: [
                            { command: 'includeDetail', label: '导出单据（含明细）' },
                            { command: 'noDetail', label: '导出单据（不含明细）' },
                        ],
                        method: command => {
                            _this.handleExportEvent(command);
                        },
                    },
                    {
                        id: "print",
                        icon: 'el-icon-printer',
                        show: true,
                        label: '打印',
                        class: 'print_btn',
                        permission: "jxc:buyReturn:print",
                        btnType: 'print',
                        printType: 'buyReturn',
                        dropdownItems: [
                            {
                                command: 'printTemplate',
                                label: '打印模板',
                                divided: true,
                                icon: 'el-icon-s-tools',
                                permission: 'jxc:buyReturn:printTemplate'
                            },
                            {
                                command: 'printItem',
                                label: '打印配置项',
                                icon: 'el-icon-s-tools',
                                permission: 'jxc:buyReturn:printItem'
                            },
                        ],
                        method: command => {
                            _this.handlePrintEvent(command);
                        },
                    },
                ],
                toolbar_filter: [
                    { type: "text", field: "code", label: "退货单号" },
                    { type: "daterange", field: "return_date", label: "退货日期", style: { width: '200px' }, },
                    {
                        type: "selectBottom",
                        field: "supplier_sid",
                        label: "供应商",
                        props: {
                            type: 'supplierDrawer',
                            options: {
                                placeholder: '选择供应商',
                            },
                        },
                    },
                ],
            },
            searchForm: {
                audit_state: '',
            },
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: "JxcBuyReturnBillTable",
                container: ".jxc_buy_return_bill_container",
                multiSelect: true,
                showSummary: true,
                summaryArray: [ "qty", "amount", "pre_freight", "real_freight",
                    "total_amount", "ignore_amount", "should_return_amount",
                    "un_return_amount", "return_amount" ],
                columns: [
                    {
                        label: "状态",
                        prop: "audit_state",
                        align: "center",
                        width: 60,
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.audit_state) && row.audit_state === 1) {
                                return '已审核';
                            }
                            return '待审核';
                        },
                    },
                    {
                        label: "出库单",
                        prop: "out_bill",
                        align: "center",
                        width: 70,
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.out_bill)) {
                                if (row.out_bill === 1) {
                                    return '部分生成';
                                }
                                if (row.out_bill === 2) {
                                    return '全部生成';
                                }
                            }
                            return '未生成';
                        },
                    },
                    {
                        label: "对账单",
                        prop: "gen_finance",
                        align: "center",
                        width: 60,
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.gen_finance) && row.gen_finance === 1) {
                                return '已生成';
                            }
                            return '未生成';
                        },
                    },
                    {
                        label: "退货单号",
                        prop: "code",
                        align: "center",
                        minWidth: 160,
                    },
                    {
                        label: "退货日期",
                        prop: "return_date",
                        align: "center",
                        minWidth: 90,
                    },
                    {
                        label: "供应商",
                        prop: "supplier_display",
                        align: "center",
                    },
                    {
                        label: "供应商联系人",
                        prop: "supplier_contract_name",
                        align: "center",
                        minWidth: 116,
                    },
                    {
                        label: "供应商联系电话",
                        prop: "supplier_contract_phone",
                        align: "center",
                        minWidth: 116,
                    },
                    {
                        label: "合计数量",
                        prop: "qty",
                        align: "center",
                    },
                    {
                        label: "合计金额",
                        prop: "amount",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "预估运费",
                        prop: "pre_freight",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "实付运费",
                        prop: "real_freight",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "包邮",
                        prop: "free_shipping",
                        align: "center",
                        formatter(row) {
                            if (row.free_shipping === 1) {
                                return '是';
                            }
                            return '否';
                        },
                    },
                    {
                        label: "退货单金额",
                        prop: "total_amount",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "抹零",
                        prop: "ignore_amount",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "应退金额",
                        prop: "should_return_amount",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "已退金额",
                        prop: "return_amount",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "未退金额",
                        prop: "un_return_amount",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "发货方式",
                        prop: "delivery_mode",
                        align: "center",
                    },
                    {
                        label: "备注",
                        prop: "note_info",
                        align: "left",
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: "detail",
                            icon: "fa fa-info-circle",
                            type: "warning",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "详情",
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'detail');
                            },
                        },
                        {
                            id: "edit",
                            icon: "fa fa-pencil",
                            type: "success ",
                            size: "mini",
                            show: true,
                            permission: "jxc:buyReturn:save",
                            tooltip: {
                                content: "编辑",
                            },
                            filter(row) {
                                return row.audit_state === 0;
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'edit');
                            },
                        },
                        {
                            id: "del",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            size: "mini",
                            show: true,
                            permission: "jxc:buyReturn:delete",
                            tooltip: {
                                content: "删除",
                            },
                            filter(row) {
                                return row.audit_state === 0;
                            },
                            method: (index, row) => {
                                _this.deleteConfirm(row);
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
        };
    },
    computed: {
        ...mapState('jxc', [ 'stateList' ]),
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            const _this = this;
            _this.$bus.$off(`refreshJxcBuyReturnBill`);
            _this.$bus.$on(`refreshJxcBuyReturnBill`, () => {
                _this.getList(true);
            });
            _this.getList(true);
        },
        handleHeaderEvent(event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        getList(query) {
            const _this = this;
            if (query) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            _this.fetchData(_this.$api.API_FindJxcBuyReturnBills, queryData).then(result => {
                _this.dataList = result.data || [];
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        openDialog(row, type) {
            const _this = this;
            if (type === 'edit' && row == null) {
                if (!_this.checkSelection(_this.selectionList, false)) {
                    return;
                }
                row = _this.selectionList[0];
            }
            if (!row) {
                row = {};
            }
            if (type === 'edit' && row.audit_state === 1) {
                _this.$message.error(`退货单：${ row.code } 已审核，请先反审核再编辑！`);
                return;
            }
            let detail = type === 'detail' || row.audit_state === 1;
            const query = {};
            if (_this.$utils.isNotEmpty(row.sid)) {
                query.sid = row.sid;
            }
            _this.$router.push({
                path: `/jxcBuyReturnBillDetail${detail?'View':''}`,
                query,
            });
            // _this.$dialog({
            //     title: '采购退货单',
            //     width: '1000px',
            //     component: {
            //         value: BuyReturnBillForm,
            //         props: {
            //             detail,
            //             row,
            //         },
            //     },
            //     hideConfirmBtn: detail,
            //     confirmed() {
            //         _this.getList();
            //         _this.$bus.$emit('updateJxcDashboard');
            //     },
            // });
        },
        deleteConfirm(row) {
            const _this = this;
            if (row) {
                if (row.out_bill === 1 || row.out_bill === 2) {
                    _this.$message.error('采购退货单：' + row.code + '已经有部分出库或者全部出库，无法删除！');
                    return;
                }
            } else {
                let filterList = _this.selectionList.filter(item => item.gen_finance === 1);
                if (_this.$utils.isNotEmptyList(filterList)) {
                    let codeList = filterList.map(item => item.code);
                    _this.$message.error(`采购退货单：${ codeList.join('、') } 已生成对账，无法删除！`);
                    return;
                }
                filterList = _this.selectionList.filter(item => item.in_bill === 1 || item.in_bill === 2);
                if (filterList && filterList.length > 0) {
                    let msgList = filterList.map(item => item.code);
                    _this.$message.error('采购退货单：' + msgList.join('、') + '已经有部分出库或者全部出库，无法删除！');
                    return;
                }
            }
            _this.storeDispatch('jxc/handleDeleteData', {
                url: _this.$api.API_DeleteJxcBuyReturnBills,
                row,
                list: _this.selectionList,
                _vm: _this,
                msg_name: '采购退货单',
            }).then(res => {
                if (res) {
                    _this.getList();
                    _this.$bus.$emit('updateJxcDashboard');
                }
            });
        },
        changeAuditState(type) {
            const _this = this;
            let filterList = _this.selectionList.filter(item => item.gen_finance === 1);
            if (_this.$utils.isNotEmptyList(filterList)) {
                let codeList = filterList.map(item => item.code);
                _this.$message.error(`采购退货单：${ codeList.join('、') } 已生成对账，无法${ type === 'audit' ? '审核' : '反审' }！`);
                return;
            }
            filterList = _this.selectionList.filter(item => item.out_bill === 1 || item.out_bill === 2);
            if (filterList && filterList.length > 0) {
                let codeList = filterList.map(item => item.code);
                _this.$message.error(`采购退货单：${ codeList.join('、') } 已经有部分出库或者全部出库，无法${ type === 'audit' ? '审核' : '反审' }！`);
                return;
            }
            _this.storeDispatch('jxc/changeAuditState', {
                url: _this.$api.API_ChangeJxcBuyReturnBillAuditState,
                list: _this.selectionList,
                type,
                _vm: _this,
                msg_name: '采购退货单',
            }).then(res => {
                if (res) {
                    _this.getList();
                }
            });
        },
        genOutBill() {
            const _this = this;
            if (!_this.$utils.isVersionAuthPath("/jxcStockOutBill")){
                return;
            }
            if (!_this.checkSelection(_this.selectionList, true)) {
                return;
            }
            let filterList = _this.selectionList.filter(item => item.audit_state === 0);
            if (_this.$utils.isNotEmptyList(filterList)) {
                let codeList = filterList.map(item => item.code);
                _this.$message.error(`采购退货单：${ codeList.join('、') } 未审核，无法生成出库单！`);
                return;
            }
            filterList = _this.selectionList.filter(item => item.in_bill === 2);
            if (_this.$utils.isNotEmptyList(filterList)) {
                let codeList = filterList.map(item => item.code);
                _this.$message.error(`采购退货单：${ codeList.join('、') } 已全部出库！`);
                return;
            }
            let sid_list = _this.selectionList.map(item => item.sid);
            _this.fetchData(_this.$api.API_GenJxcBuyReturnBill2OutBill, {
                sid_list,
            }).then(() => {
                _this.$message.success('生成出库单成功！');
                _this.getList();
            }).catch(() => {
            });
        },
        genFinance() {
            const _this = this;
            if (!_this.checkSelection(_this.selectionList, true)) {
                return;
            }
            let filterList = _this.selectionList.filter(item => item.gen_finance === 1);
            if (_this.$utils.isNotEmptyList(filterList)) {
                let codeList = filterList.map(item => item.code);
                _this.$message.error(`采购退货单：${ codeList.join('、') } 已生成对账！`);
                return;
            }
            filterList = _this.selectionList.filter(item => item.audit_state === 0);
            if (_this.$utils.isNotEmptyList(filterList)) {
                let codeList = filterList.map(item => item.code);
                _this.$message.error(`采购退货单：${ codeList.join('、') } 未审核，无法生成对账！`);
                return;
            }
            let sid_list = _this.selectionList.map(item => item.sid);
            _this.fetchData(_this.$api.API_GenJxcFinanceAccountDetail4BuyReturn, {
                sid_list,
            }).then((res) => {
                _this.$message.success('本次生成对账单数量：' + res.data);
                _this.getList();
            }).catch(() => {
            });
        },
        handleExportEvent(command) {
            const _this = this;
            let queryData = $.extend({}, _this.searchForm);
            queryData.dr = 0;
            let url = _this.$api.API_FindJxcBuyReturnBillsInclude;
            let outputName = '采购退货单（含明细）';
            let templateName = _this.$api.EXPORT_TEMPLATE_NAME_BUY_RETURN_INCLUDE_DETAIL;
            if (command === 'noDetail') {
                url = _this.$api.API_FindJxcBuyReturnBills;
                outputName = '采购退货单（不含明细）';
                templateName = _this.$api.EXPORT_TEMPLATE_NAME_BUY_RETURN_NO_DETAIL;
            }
            poiApi.exportExcelTemplate(templateName, url, queryData, outputName, {}, undefined, 1, 100, false, true).then(() => {
                return true;
            }).catch(() => {
                return false;
            });
        },
        handlePrintEvent(command) {
            const _this = this;
            if (command === 'printTemplate') {
                _this.$router.push({
                    path: '/print/buyReturn',
                    query: {
                        name: '采购退货单',
                    },
                });
                return;
            }
            if (command === 'printItem') {
                _this.$router.push({
                    path: '/printItem/buyReturn',
                    query: {
                        name: '采购退货单',
                    },
                });
                return;
            }
            if (!_this.checkSelection(_this.selectionList, true)) {
                return;
            }
            _this.$PrintPreview({
                template: command.sid,
                data: _this.selectionList,
                fetch(data) {
                    return _this.fetchData(_this.$api.API_QueryJxcBuyReturnBillData4Print, {
                        sid_list: data.map(item => item.sid),
                    }).then(result => {
                        return result.data || [];
                    }).catch(() => {
                        return [];
                    });
                },
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.jxc_buy_return_bill_container {
    width: 100%;
    height: 100%;
}
</style>
